package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class BuyMyItems extends Activity {
	
	//private TextView myListings;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.myitems);
        
        //myListings = (TextView)findViewById(R.id.myListings);
        
        SharedPreferences user = getSharedPreferences("Users", MODE_PRIVATE);
        String id = user.getString("CurrentUser", null);
       // myListings.setText(); 
          
        String result = getMyListings(id);      
         
        if(result.equals("Error in connecting...")){     
			new AlertDialog.Builder(getParent().getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();
        }
        else if (result.equals("Error in obtaining data...")){
			new AlertDialog.Builder(getParent().getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();
        }
        else if (result.equals("No replies yet. Post something!\n")){
        	/*
			new AlertDialog.Builder(BuyMyItems.this)
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();*/
        	
        	Toast.makeText(
					getApplicationContext(),
					"You have not replied to any listings yet!",
					Toast.LENGTH_SHORT)
					.show();
        	
        }
        else{
        	ListView list = (ListView)findViewById(R.id.list);
        	
        	//ArrayAdapter<String> l = new ArrayAdapter<String>(this, R.layout.books,);
        	
        	 List<Listing> listings = new ArrayList<Listing>();
              	        	
        	try{
        		JSONArray jArray = new JSONArray(result);
        		for(int i=jArray.length()-1;i>=0;i--){
        			JSONObject json_data = jArray.getJSONObject(i);
        			//String R_id = json_data.getString("R_id");
        			String L_id = json_data.getString("L_id");
        			String cat = json_data.getString("cat");
        			String title = json_data.getString("title");
        			String text = json_data.getString("text");
        			String U_id = json_data.getString("U_id");
        			String time = json_data.getString("time");
        			//listings.append(L_id + " | " + cat + " | " + title + " | " + text + " | " + U_id + " | " + time + "\n");
        			
        			listings.add(new Listing(L_id,"", U_id,cat,title,text,time));
        		}
        	}
        	catch(JSONException e){
        		/*
    			new AlertDialog.Builder(BuyMyItems.this)
    			.setMessage("Error in parsing data!")  
    			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int id) {
    				}
    			})
    			.show();
    			*/
        		
        		Toast.makeText(
    					getApplicationContext(),
    					"You have not replied to any listings yet!",
    					Toast.LENGTH_SHORT)
    					.show();
            	
        		
        		
        		Log.e("log_tag", "Error parsing data "+e.toString());
        	}
        	
        	Listings adapter = new Listings(this, listings);            
            list.setAdapter(adapter);

            list.setOnItemClickListener(new OnItemClickListener() {            	
            	public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            		
    				Listing entry = (Listing) a.getItemAtPosition(position);

    				Intent i = new Intent(BuyMyItems.this, ReplyThread.class);
    				//YOUR ID
    				//i.putExtra("id", id);
    				//ID OF PERSON REPLYING TO YOU
    				i.putExtra("U_id", entry.getU_id());
    				i.putExtra("P_id", entry.getId());
    				i.putExtra("cat", entry.getCat());
    				//i.putExtra("title", entry.getTitle());
    				//i.putExtra("text", entry.getText());
    				//i.putExtra("time", entry.getTime());
    				//startActivityForResult(i, 0);
    				View view = BuyMyGroup.group.getLocalActivityManager()
    				.startActivity("ReplyThread", i
    						.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
    						.getDecorView();
    				BuyMyGroup.group.replaceView(view);
            		
            	}
            });
        }
	}
	
	public static final String MYREPLIES = "http://www.upennakpsi.org/lololol/pennmarketplace/myreplies.php";
	
	private String getMyListings (String id) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> myListings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(MYREPLIES);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//myListings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}

		return result;
	}
}